<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 系统角色管理 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="search-box">
                <div class="searchDiv">
                    <el-form :inline="true">
                        <el-form-item label="角色名称">
                            <el-input
                                v-model="searchSet.name"
                                prefix-icon="el-icon-search"
                                clearable
                                placeholder="请输入角色名称"
                            ></el-input>
                        </el-form-item>

                        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                        <el-button type="primary" icon="el-icon-plus" @click="handleAddNew">新增角色</el-button>
                    </el-form>
                </div>
            </div>
            <el-table
                :data="tableData"
                v-loading="tableLoading"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
            >
                <!-- <el-table-column prop="id"
                         label="角色ID"
                         align="center"></el-table-column> -->
                <el-table-column prop="name" label="角色名称" align="center"></el-table-column>
                <!-- <el-table-column prop="order"
                         label="排序"
                         align="center"></el-table-column> -->
                <el-table-column
                    prop="isdefault"
                    label="是否管理员"
                    :formatter="
                        (r, c, v, i) => {
                            return Number(v) == 0 ? '否' : '是';
                        }
                    "
                    align="center"
                ></el-table-column>
                <el-table-column prop="addtime" label="添加时间" align="center"></el-table-column>
                <el-table-column label="状态" width="70" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="statusList[scope.row.status] ? statusList[scope.row.status].tagtype : 'info'">
                            {{ statusList[scope.row.status] ? statusList[scope.row.status].name : '无效' }}</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="210" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button
                            type="text"
                            v-if="scope.row.isdefault != 1"
                            icon="el-icon-postcard"
                            class="color-Warning"
                            @click="handlePermission(scope.$index, scope.row)"
                            >权限设置</el-button
                        >
                        <el-button
                            type="text"
                            v-if="scope.row.isdefault != 1"
                            icon="el-icon-delete"
                            class="color-red"
                            @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="sizes, total, prev, pager, next"
                    :current-page="query.index"
                    :page-sizes="[10, 20, 30, 40, 50, 100]"
                    :page-size="query.pageSize"
                    :total="itemTotal"
                    @current-change="handlePageChange"
                    @size-change="handlePageSizeChange"
                ></el-pagination>
            </div>
        </div>
        <el-dialog :title="editIsNewAdd ? '新增角色' : '编辑角色'" v-dialogDrag center :visible.sync="editVisible" width="60%">
            <el-form ref="form" :model="form" :rules="formRules" label-width="120px">
                <el-form-item label="角色名称" prop="name">
                    <el-input
                        v-model="form.name"
                        placeholder="请填写角色名称"
                        maxlength="30"
                        show-word-limit
                        clearable
                        class="formInput"
                    ></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="角色权限编辑" v-dialogDrag center :visible.sync="editPermissionVisible" width="60%">
            <el-form
                ref="formPermission"
                v-loading="permissionLoading"
                element-loading-text="角色权限内容加载中"
                :model="formPermission"
                label-width="120px"
            >
                <el-form-item label="角色ID" prop="id">
                    <el-input v-model="formPermission.id" disabled class="formInput"></el-input>
                </el-form-item>
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="formPermission.name" disabled class="formInput"></el-input>
                </el-form-item>
                <el-form-item label="权限设置">
                    <el-tree
                        ref="tree"
                        :props="formPermissionProps"
                        :accordion="false"
                        node-key="treeid"
                        @check-change="TreeCheckChange"
                        :default-checked-keys="TreeDefaultCheck"
                        show-checkbox
                        :data="formPermission.details"
                    >
                    </el-tree>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editPermissionVisible = false">取 消</el-button>
                <el-button type="primary" @click="savePermission">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import API from '../../../api/index'; //读入restfulAPI
import StringTool from '../../../utils/StringTool';
import JSTool from '../../../utils/JSTool';
import detailDialog from '../../common/dialog/detailDialog.vue';
import dataTable from './dataTable';
export default {
    name: 'appuser',
    mixins: [dataTable],
    components: {
        detailDialog
    },
    data() {
        return {
            searchSet: {
                name: ''
            },
            query: {
                status: 1,
                index: 1,
                pageSize: 10
            },
            statusList: { 0: { name: '无效', id: '0', tagtype: 'info' }, 1: { name: '正常', id: '1', tagtype: 'success' } },
            editVisible: false,
            editIsNewAdd: false,

            form: {
                name: ''
            },
            formRules: {
                name: [
                    { required: true, message: '参数不能为空', trigger: 'change' },
                    { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'change' }
                ]
            },
            permissionLoading: true,
            editPermissionVisible: false,
            TreeDefaultCheck: [],
            formPermission: {},
            formPermissionProps: {
                label: (data, node) => {
                    return data.name || data.functionName;
                },
                children: 'subs'
            }
        };
    },
    created() {
        this.init();
    },
    mounted() {},
    methods: {
        loadNode(node, resolve) {
            console.log(node);
            if (node.level === 0) {
                this.permissionLoading = true;
                API.StandardDoWith(API.PermissionManage.Get({ id: this.formPermission.id }), this, {
                    success: (detail) => {
                        this.formPermission = detail;
                        return resolve(this.convertTreeObj(detail.details));
                    },
                    complete: () => {
                        this.permissionLoading = false;
                    }
                });
            } else {
                return resolve(node.data.children);
            }
        },

        //页面初始化
        init() {
            this.getData();
        },
        handleAddNew() {
            this.editVisible = true;
            this.editIsNewAdd = true;
            this.form = {
                name: ''
            };
        },
        handleEdit(index, row) {
            this.form = { id: row.id, name: row.name }; //仅单层拷贝
            this.editVisible = true;
            this.editIsNewAdd = false;
        },
        getData() {
            this.tableLoading = true;
            API.StandardDoWith(API.RoleManage.Get(this.getQuery()), this, {
                success: (detail) => {
                    this.itemTotal = detail.count;
                    this.tableData = detail.list;
                },
                complete: () => {
                    this.tableLoading = false;
                }
            });
        },

        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.requestDelete({ id: row.id });
                })
                .catch(() => {});
        },
        // 保存编辑
        saveEdit() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let form = Object.assign({}, this.form);
                    if (this.editIsNewAdd) {
                        this.requestAddNew(form);
                    } else {
                        this.requestModify(form);
                    }
                } else {
                    this.$message.error(`表单验证失败，无法提交`);
                    return false;
                }
            });
        },
        requestAddNew(data) {
            API.StandardDoWith(API.RoleManage.Post(data), this, {
                loading: '新建角色处理中',
                success: (detail) => {
                    this.editVisible = false;
                    this.$message.success(`新建角色成功`);
                    this.getData();
                }
            });
        },
        requestModify(data) {
            API.StandardDoWith(API.RoleManage.Put(data), this, {
                loading: '编辑角色处理中',
                success: (detail) => {
                    this.editVisible = false;
                    this.$message.success(`编辑角色成功`);
                    this.getData();
                }
            });
        },
        requestDelete(params) {
            //计算是否为删除表格最后一页的单项，进行自动回退页面
            let autoBackPrevPage = this.isLastPageSingleItem();

            API.StandardDoWith(API.RoleManage.Delete(params), this, {
                loading: '删除处理中',
                success: (detail) => {
                    this.$message.success(`删除数据成功`);
                    if (autoBackPrevPage) {
                        this.$set(this.query, 'index', this.query.index - 1);
                    }
                    this.getData();
                }
            });
        },
        handlePermission(index, row) {
            this.formPermission = { id: row.id, name: row.name, details: [] };

            this.editPermissionVisible = true;
            this.permissionLoading = true;
            API.StandardDoWith(API.PermissionManage.Get({ id: this.formPermission.id }), this, {
                success: (detail) => {
                    this.TreeDefaultCheck = [];
                    this.formPermission.details = this.convertTreeObj(detail.details);
                    // this.TreeDefaultCheck = checkObjList
                },
                complete: () => {
                    this.permissionLoading = false;
                }
            });
        },
        convertTreeObj(obj) {
            obj.map((it) => {
                if (it.isdirectory == 1) {
                    it.subs = this.convertTreeObj(it.subs);
                } else if (it.isdirectory == 0 && it.functions) {
                    it.functions.map((fun) => {
                        if (fun.isChecked) {
                            fun.treeid = String(it.id) + '/' + String(fun.functionid);
                            this.TreeDefaultCheck.push(fun.treeid);
                        }
                    });
                    it.subs = it.functions;
                }
            });
            return obj;
        },
        AllItemCheck(data, isCheck) {
            if (data.functionid) {
                data.isChecked = isCheck;
            } else {
                data.subs.map((it) => {
                    this.AllItemCheck(it, isCheck);
                });
            }
        },
        TreeCheckChange(data, selfCheck, childCheck) {
            this.AllItemCheck(data, selfCheck);
        },
        TreePutDoWith(obj) {
            obj.map((it) => {
                if (it.isdirectory == 0) {
                    it.functions = it.subs;
                    it.functions.map((fun) => {
                        delete fun.treeid;
                    });
                    it.subs = [];
                } else if (it.isdirectory == 1) {
                    this.TreePutDoWith(it.subs);
                }
            });
        },
        savePermission() {
            console.log(this.formPermission);
            let obj = JSTool.DeepClone(this.formPermission);
            this.TreePutDoWith(obj.details);
            console.log(obj);
            API.StandardDoWith(API.PermissionManage.Put(obj), this, {
                loading: '权限处理中',
                success: (detail) => {
                    this.editPermissionVisible = false;
                    this.$message.success(`权限处理成功`);
                }
            });
        }
    }
};
</script>

<style scoped>
@import '../../../assets/css/dataTable.css';
</style>
